// tt-avchat-demoDlg.cpp : 实现文件
//

#include "stdafx.h"
#include "tt-avchat-demo.h"
#include "tt-avchat-demoDlg.h"
#include "afxdialogex.h"

#include <string>

#ifdef _DEBUG
#define new DEBUG_NEW
#endif


static IceServers iceServers;

// 用于应用程序“关于”菜单项的 CAboutDlg 对话框

class CAboutDlg : public CDialogEx
{
public:
	CAboutDlg();

// 对话框数据
	enum { IDD = IDD_ABOUTBOX };

	protected:
	virtual void DoDataExchange(CDataExchange* pDX);    // DDX/DDV 支持

// 实现
protected:
	DECLARE_MESSAGE_MAP()
};

CAboutDlg::CAboutDlg() : CDialogEx(CAboutDlg::IDD)
{
}

void CAboutDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
}

BEGIN_MESSAGE_MAP(CAboutDlg, CDialogEx)
END_MESSAGE_MAP()


// CttavchatdemoDlg 对话框



CttavchatdemoDlg::CttavchatdemoDlg(CWnd* pParent /*=NULL*/)
	: CDialogEx(CttavchatdemoDlg::IDD, pParent)
{
	m_hIcon = AfxGetApp()->LoadIcon(IDR_MAINFRAME);
}

void CttavchatdemoDlg::DoDataExchange(CDataExchange* pDX)
{
	CDialogEx::DoDataExchange(pDX);
	DDX_Control(pDX, IDC_STATIC_VIDEO_RENDERER, mVideoRenderer);
	DDX_Control(pDX, IDC_STATIC_STATUS, mStatusLabel);
}

BEGIN_MESSAGE_MAP(CttavchatdemoDlg, CDialogEx)
	ON_WM_SYSCOMMAND()
	ON_WM_PAINT()
	ON_WM_QUERYDRAGICON()
	ON_BN_CLICKED(IDC_BUTTON_CREATE_CALL, &CttavchatdemoDlg::OnBnClickedButtonCreateCall)
	ON_BN_CLICKED(IDC_BUTTON_ANSWER_CALL, &CttavchatdemoDlg::OnBnClickedButtonAnswerCall)
	ON_BN_CLICKED(IDC_BUTTON_HANGUP, &CttavchatdemoDlg::OnBnClickedButtonHangup)
	ON_BN_CLICKED(IDC_BUTTON_LOOPBACK, &CttavchatdemoDlg::OnBnClickedButtonLoopback)
	ON_WM_CLOSE()
END_MESSAGE_MAP()


// CttavchatdemoDlg 消息处理程序

BOOL CttavchatdemoDlg::OnInitDialog()
{
	CDialogEx::OnInitDialog();

	// 将“关于...”菜单项添加到系统菜单中。

	// IDM_ABOUTBOX 必须在系统命令范围内。
	ASSERT((IDM_ABOUTBOX & 0xFFF0) == IDM_ABOUTBOX);
	ASSERT(IDM_ABOUTBOX < 0xF000);

	CMenu* pSysMenu = GetSystemMenu(FALSE);
	if (pSysMenu != NULL)
	{
		BOOL bNameValid;
		CString strAboutMenu;
		bNameValid = strAboutMenu.LoadString(IDS_ABOUTBOX);
		ASSERT(bNameValid);
		if (!strAboutMenu.IsEmpty())
		{
			pSysMenu->AppendMenu(MF_SEPARATOR);
			pSysMenu->AppendMenu(MF_STRING, IDM_ABOUTBOX, strAboutMenu);
		}
	}

	// 设置此对话框的图标。  当应用程序主窗口不是对话框时，框架将自动
	//  执行此操作
	SetIcon(m_hIcon, TRUE);			// 设置大图标
	SetIcon(m_hIcon, FALSE);		// 设置小图标

	TTAVEngineSDK::Initialize();

	IceServer server;
	server.uri = "turn:stun.l.google.com:19302";
	server.username = "700";
	server.password = "700";
	iceServers.push_back(server);

	IceServer server2;
	server.uri = "stun:stun.l.google.com:19302";
	iceServers.push_back(server2);

	local_renderer_.reset(new VideoRendererForWindows(this));
	remote_renderer_.reset(new VideoRendererForWindows(this));

	ddh_ = DrawDibOpen();

	return TRUE;  // 除非将焦点设置到控件，否则返回 TRUE
}

void CttavchatdemoDlg::OnSysCommand(UINT nID, LPARAM lParam)
{
	if ((nID & 0xFFF0) == IDM_ABOUTBOX)
	{
		CAboutDlg dlgAbout;
		dlgAbout.DoModal();
	}
	else
	{
		CDialogEx::OnSysCommand(nID, lParam);
	}
}

// 如果向对话框添加最小化按钮，则需要下面的代码
//  来绘制该图标。  对于使用文档/视图模型的 MFC 应用程序，
//  这将由框架自动完成。

void CttavchatdemoDlg::OnPaint()
{
	if (IsIconic())
	{
		CPaintDC dc(this); // 用于绘制的设备上下文

		SendMessage(WM_ICONERASEBKGND, reinterpret_cast<WPARAM>(dc.GetSafeHdc()), 0);

		// 使图标在工作区矩形中居中
		int cxIcon = GetSystemMetrics(SM_CXICON);
		int cyIcon = GetSystemMetrics(SM_CYICON);
		CRect rect;
		GetClientRect(&rect);
		int x = (rect.Width() - cxIcon + 1) / 2;
		int y = (rect.Height() - cyIcon + 1) / 2;

		// 绘制图标
		dc.DrawIcon(x, y, m_hIcon);
	}
	else
	{
		CDialogEx::OnPaint();
	}
}

//当用户拖动最小化窗口时系统调用此函数取得光标
//显示。
HCURSOR CttavchatdemoDlg::OnQueryDragIcon()
{
	return static_cast<HCURSOR>(m_hIcon);
}

static Call *current_call = NULL;

void CttavchatdemoDlg::OnBnClickedButtonCreateCall()
{
	CallFactory *call_factory = TTAVEngineSDK::GetCallFactory();
	if (!current_call)
	{
		/*创建外呼Call*/
		current_call = call_factory->Create(kOutgoing, iceServers);
		//current_call->RegisterVideoRenderer(local_renderer_.get(), remote_renderer_.get(), kARGB);
		current_call->SetCallEventObserver(this);
		current_call->CreatePeerConnection();
	}
}

std::string offer_sdp;
std::string answer_sdp;
static Call *current_call2 = NULL;
void CttavchatdemoDlg::OnBnClickedButtonAnswerCall()
{
	CallFactory *call_factory = TTAVEngineSDK::GetCallFactory();
	if (!current_call2 && current_call)
	{
		/*创建接听Call*/
		current_call2 = call_factory->Create(kIncoming, iceServers);
		current_call->RegisterVideoRenderer(local_renderer_.get(), remote_renderer_.get(), kARGB);
		current_call2->SetCallEventObserver(this);
		current_call2->CreatePeerConnection();
		current_call2->SetRemoteSDP((const char *)offer_sdp.c_str(), offer_sdp.length());
	}
}

void CttavchatdemoDlg::OnOfferSDP(const char * offer, int len)
{
	offer_sdp.assign(offer, len);
}

void CttavchatdemoDlg::OnAnswerSDP(const char *offer, int len)
{
	answer_sdp.assign(offer, len);
	current_call->SetRemoteSDP((const char *)answer_sdp.c_str(), answer_sdp.length());
}

void CttavchatdemoDlg::OnFailure(ErrorMessageType type, const char *message)
{
	/*呼叫错误信息*/
}

void CttavchatdemoDlg::OnBnClickedButtonHangup()
{
	CallFactory *call_factory = TTAVEngineSDK::GetCallFactory();

	if (current_call)
	{
		current_call->DisconnectPeerConnection();
		call_factory->Delete(current_call);
		current_call = NULL;
	}
}

void CttavchatdemoDlg::OnBnClickedButtonLoopback()
{
	CallFactory *call_factory = TTAVEngineSDK::GetCallFactory();
	if (!current_call)
	{
		/*创建外呼Call*/
		current_call = call_factory->Create(kLoopBack, iceServers);
		current_call->RegisterVideoRenderer(local_renderer_.get(), remote_renderer_.get(), kARGB);
		current_call->SetCallEventObserver(this);
		current_call->CreatePeerConnection();
	}
}

#define ARRAY_SIZE(x) (static_cast<int>(sizeof(x) / sizeof(x[0])))
#define LOCAL_BORDER_SIZE 2

void CttavchatdemoDlg::DrawVideoFrame(HWND wnd)
{
	HDC hdc = ::GetDC(wnd);

	RECT rc;
	::GetClientRect(wnd, &rc);

	VideoRendererForWindows* local_renderer =  local_renderer_.get();
	VideoRendererForWindows* remote_renderer = remote_renderer_.get();
	
	if (remote_renderer && local_renderer)
	{
		AutoLock<VideoRendererForWindows> remote_lock(remote_renderer);

		const BITMAPINFO& bmi = remote_renderer->bmi();
		int height = abs(bmi.bmiHeader.biHeight);
		int width = bmi.bmiHeader.biWidth;

		const unsigned char* image = remote_renderer->image();
		if (image != NULL) {
			POINT logical_area = { rc.right, rc.bottom };
			DPtoLP(hdc, &logical_area, 1);

			RECT logical_rect = { 0, 0, logical_area.x, logical_area.y };

			/*渲染黑色背景*/
			HBRUSH brush = ::CreateSolidBrush(RGB(0, 0, 0));			
			::FillRect(hdc, &logical_rect, brush);
			::DeleteObject(brush);

			/*
			根据渲染控件的尺寸，重新计算长宽比例
			*/
			int dst_width, dst_height;
			dst_width = rc.right & ~0x3;
			dst_height = ((dst_width * height) / width) & ~0x1;
			if (dst_height > rc.bottom){
				dst_height = rc.bottom & ~0x1;
				dst_width = ((dst_height*width) / height) & ~0x3;
			}

			/*计算视频帧显示位置*/
			int x = (logical_area.x / 2) - (dst_width / 2);
			int y = (logical_area.y / 2) - (dst_height / 2);

			DrawDibDraw(ddh_, hdc, x, y, dst_width, dst_height, (LPBITMAPINFOHEADER)&bmi.bmiHeader, (LPVOID)image,
				0, 0, width, height, 0);
		    
			AutoLock<VideoRendererForWindows> local_lock(local_renderer);
			/*渲染本地视频*/
			if ((rc.right - rc.left) > 200 && (rc.bottom - rc.top) > 200
				&& local_renderer->image() !=NULL )
			{
				const BITMAPINFO& bmi = local_renderer->bmi();
				image = local_renderer->image();
				width = bmi.bmiHeader.biWidth;
				height = abs(bmi.bmiHeader.biHeight);
				int thumb_width =  width / 4;
				int thumb_height = height / 4;
				x = logical_area.x - thumb_width - 10;
				y = logical_area.y - thumb_height - 10;

				/*画出本地视频边框*/
				Rectangle(hdc, x - LOCAL_BORDER_SIZE, y - LOCAL_BORDER_SIZE,
					x + thumb_width + LOCAL_BORDER_SIZE,  y + thumb_height + LOCAL_BORDER_SIZE);

				DrawDibDraw(ddh_, hdc, x, y, thumb_width, thumb_height, (LPBITMAPINFOHEADER)&bmi.bmiHeader, (LPVOID)image,
					0, 0, width, height, 0);
			}
		}
		else
		{
			POINT logical_area = { rc.right, rc.bottom };
			DPtoLP(hdc, &logical_area, 1);

			HBRUSH brush = ::CreateSolidBrush(RGB(0, 0, 0));
			RECT logical_rect = { 0, 0, logical_area.x, logical_area.y };

			::FillRect(hdc, &logical_rect, brush);
			::DeleteObject(brush);

			AutoLock<VideoRendererForWindows> local_lock(local_renderer);
			int x, y, width, height;
			/*渲染本地视频*/
			if ((rc.right - rc.left) > 200 && (rc.bottom - rc.top) > 200
				&& local_renderer->image() != NULL)
			{
				const BITMAPINFO& bmi = local_renderer->bmi();
				image = local_renderer->image();
				width = bmi.bmiHeader.biWidth;
				height = abs(bmi.bmiHeader.biHeight);
				int thumb_width = width / 4;
				int thumb_height = height / 4;
				x = logical_area.x - thumb_width - 10;
				y = logical_area.y - thumb_height - 10;

				/*画出本地视频边框*/
				Rectangle(hdc, x - LOCAL_BORDER_SIZE, y - LOCAL_BORDER_SIZE,
					x + thumb_width + LOCAL_BORDER_SIZE, y + thumb_height + LOCAL_BORDER_SIZE);

				DrawDibDraw(ddh_, hdc, x, y, thumb_width, thumb_height, (LPBITMAPINFOHEADER)&bmi.bmiHeader, (LPVOID)image,
					0, 0, width, height, 0);
			}

		}
	}
}


void CttavchatdemoDlg::OnClose()
{
	DrawDibClose(ddh_);
	__super::OnClose();
}

void CttavchatdemoDlg::OnVideoFrame()
{
	/*将视频渲染到指定控件上*/
	DrawVideoFrame(mVideoRenderer.m_hWnd);
}